package com.yc.testupload.crawler.strategy;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 处理通用题目-答案格式的网页的爬取策略
 */
public class CommonQuestionAnswerStrategy implements CrawlingStrategy {
    private static final Logger logger = LogManager.getLogger(CommonQuestionAnswerStrategy.class);
    
    @Override
    public boolean isApplicable(String url) {
        // 这个策略是通用的，可以用于大多数网页
        // 在策略选择器中，它通常会被放在后面作为备选
        return true;
    }
    
    @Override
    public String extractQuestions(String html) {
        StringBuilder result = new StringBuilder();
        
        try {
            // 优化正则表达式，避免复杂的先行断言导致的性能问题
            // 先移除HTML标签，减少处理的复杂度
            String text = html.replaceAll("<[^>]*>", "").replaceAll("\\s+", " ").trim();
            
            // 使用更简单的方式提取数字序号的题目
            Pattern numberedPattern = Pattern.compile("(\\d+\\.|\\d+、)(.*?)", Pattern.CASE_INSENSITIVE);
            Matcher numberedMatcher = numberedPattern.matcher(text);
            
            int count = 0;
            int lastEnd = 0;
            while (numberedMatcher.find(lastEnd) && count < 10) {
                int start = numberedMatcher.start();
                int end = numberedMatcher.end();
                
                // 提取题目内容（包括序号）
                String question = numberedMatcher.group(0).trim();
                
                // 尝试查找答案部分
                int answerStart = text.indexOf("答案", end);
                int answerStart2 = text.indexOf("解析", end);
                int nextQuestionStart = -1;
                
                // 查找下一个题目的开始位置
                Matcher nextMatcher = Pattern.compile("(\\d+\\.|\\d+、)", Pattern.CASE_INSENSITIVE).matcher(text);
                if (nextMatcher.find(end)) {
                    nextQuestionStart = nextMatcher.start();
                }
                
                // 提取答案（如果有）
                if (answerStart > 0 && (nextQuestionStart == -1 || answerStart < nextQuestionStart)) {
                    String answer;
                    if (nextQuestionStart > 0) {
                        answer = text.substring(answerStart, nextQuestionStart).trim();
                        lastEnd = nextQuestionStart;
                    } else {
                        answer = text.substring(answerStart).trim();
                        lastEnd = text.length();
                    }
                    result.append("题目 " + (count + 1) + ": " + question).append("\n");
                    result.append(answer).append("\n\n");
                } else if (answerStart2 > 0 && (nextQuestionStart == -1 || answerStart2 < nextQuestionStart)) {
                    String answer;
                    if (nextQuestionStart > 0) {
                        answer = text.substring(answerStart2, nextQuestionStart).trim();
                        lastEnd = nextQuestionStart;
                    } else {
                        answer = text.substring(answerStart2).trim();
                        lastEnd = text.length();
                    }
                    result.append("题目 " + (count + 1) + ": " + question).append("\n");
                    result.append(answer).append("\n\n");
                } else {
                    // 如果没有明确的答案部分，只提取题目
                    result.append("题目 " + (count + 1) + ": " + question).append("\n\n");
                    lastEnd = end;
                }
                
                count++;
            }
        } catch (Exception e) {
            logger.error("提取通用题目-答案格式时出错: {}", e.getMessage());
        }
        
        return result.toString();
    }
    
    @Override
    public String extractTitle(String html) {
        String title = "";
        Pattern titlePattern = Pattern.compile("<title>(.*?)</title>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
        Matcher titleMatcher = titlePattern.matcher(html);
        if (titleMatcher.find()) {
            title = titleMatcher.group(1).trim();
        }
        return title;
    }
}